from helpers import updateInfo
import os
from helpers import Transactions
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Buy stocks and ETF class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        select_options=""
        if self.request.get('q'):
            query = self.request.get('q')
        else:    
            query = "Stock Name (In English)"
    
        q_1 = db.GqlQuery("SELECT * FROM StocksCategories ORDER BY category")
        # Init prevCat (category name will never be empty)
        for p in q_1:
                select_options+="<option>" + p.category + "</option>\n"
        
        template_values = {
            'current_user_totalamount': current_user.totalamount,
            'stockname': query,
            'MaxAmountValue': updateInfo.maxAmountLength,
            'maxStockLength' : updateInfo.maxStockLength,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : 'Buy Stock %s' % updateInfo.createToolTip("buy"),
            'select_options': select_options,
            'setHead' : 1,
            'headContent' : 'buy_head.html',
            'maincontent' : 'account_main.html',
            'account_main_content' : 'buy_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))

    def post(self):
          
        # Error var
        isValid="A"
        
        if (self.request.get('action')=="buy"):
            try:
                    stockString = self.request.get('numofstocks').split(',')
                    for i in range (0,len(stockString)):
                        if stockString[i]=='1':
                            # Sending the stock name with lowercase
                            succ=Transactions.buyStock(users.get_current_user(), self.request.get('setext[' + str(i) + ']').lower(), self.request.get('sevalue[' + str(i) + ']'))
                            if succ==0:
                                isValid+="A0"
                                break;
                            elif succ==-1:
                                isValid+="A1"
                            elif succ==-2:
                                isValid+="A2"
                                
    
            except:
                self.redirect('/report?msg=15')
                return
                
        elif(self.request.get('action')=="buyETF"):
            succ=Transactions.buyETF(users.get_current_user(),self.request.get('categorytext'),self.request.get('ETFvalue'))
            if succ==0:
                isValid+="A0"
            elif succ==-1:
                isValid+="A4"
            elif succ==-2:
                isValid+="A2"            
            
            
        # Load main page again (Using PRG- Post/Redirect/Get)
        self.redirect('/report?msg=%s' % isValid)
        return
        

application = webapp.WSGIApplication(
                                     [('/buy', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
